import {computed, nextTick, shallowRef} from 'vue';
import $ from 'jquery';

export default function useFormZoom({formWrapper, formWrapperZoomWrapper, context}) {

  const minZoom = shallowRef(1);
  const maxZoom = shallowRef(1);
  const currentZoom = shallowRef(1);
  const message = shallowRef();
  const formWrapperHeight = shallowRef(0);

  const zoomWrapperWidth = shallowRef(0);
  const zoomWrapperHeight = shallowRef(0);

  function initZoom() {
    try {
      stop()
      if (!context.value || context.value.showLabel()) {
        currentZoom.value = 1;
        return;
      }
      handleMinAndMaxZoom();
      currentZoom.value = minZoom.value;

      listenHeightChange();
      startTouchCtrlZoom();
    } catch (e) {
    }
  }

  function stop() {
    try {
      $(getRootElement()).off('touchstart.useFormZoom')
    } catch(e) {
    }

    try {
      window.useFormZoomResizeObserver.disconnect();
    } catch(e) {
    }

  }

  function handleMinAndMaxZoom() {
    try {
      minZoom.value = getRootRect().width / getFormWrapperRect().width;
    } catch (e) {
    }

    maxZoom.value = 1;
    maxZoom.value = Math.max(maxZoom.value, minZoom.value);
  }

  function getFormWrapperRect() {
    return formWrapper.value.getBoundingClientRect();
  }

  function getRootRect() {
    return formWrapperZoomWrapper.value.parentNode.getBoundingClientRect();
  }

  function getRootElement() {
    return $(formWrapperZoomWrapper.value).parent()[0];
  }

  function startTouchCtrlZoom() {
    // let rootEle = formWrapper.value;
    let rootEle = getRootElement();
    let initialDistance = 0;
    let originX = 0
    let originY = 0
    let scale = 1

    let touchend = () => {
      // setMessage('touchend');
      $(rootEle).off('touchmove.useFormZoom')
      $(rootEle).off('touchend.useFormZoom')
      $(getRootElement()).css({
        'transform': `scale(1)`,
        'transform-origin': '',
      })

      let temp = Math.max(minZoom.value, Math.min(maxZoom.value, currentZoom.value * scale));
      setMessage(scale + "->" + temp + "_" + currentZoom.value);
      currentZoom.value = temp
      nextTick(() => {
        handleFormWrapperZoomWrapperSize()
      })
    }
    let touchmove = e => {
      // setMessage('touchmove');
      if (e.originalEvent.touches.length === 2) {
        e.preventDefault();
        const touch1 = e.originalEvent.touches[0];
        const touch2 = e.originalEvent.touches[1];
        const currentDistance = Math.sqrt(
          Math.pow(touch1.pageX - touch2.pageX, 2) +
          Math.pow(touch1.pageY - touch2.pageY, 2)
        );
        scale = currentDistance / initialDistance;
        $(getRootElement()).css({
          'transform': `scale(${scale})`,
        })
      }
    }

    let touchstart = e => {
      if (context.value.showLabel()) {
        currentZoom.value = 1;
        handleFormWrapperZoomWrapperSize();
        stop();
        return;
      }
      // setMessage('touchstart');
      if (e.originalEvent.touches.length === 2) {
        e.preventDefault();
        const touch1 = e.originalEvent.touches[0];
        const touch2 = e.originalEvent.touches[1];
        initialDistance = Math.sqrt(
          Math.pow(touch1.pageX - touch2.pageX, 2) +
          Math.pow(touch1.pageY - touch2.pageY, 2)
        );
        originX = (touch1.pageX + touch2.pageX) / 2;
        originY = (touch1.pageY + touch2.pageY) / 2;
        let {x, y, width, height} = getRootRect()
        originX = (originX - x) * 100 / width
        originY = (originY - y)  * 100 / height
        $(getRootElement()).css({
          'transform-origin': `${originX}% ${originY}%`,
        })
        setMessage(`${originX}%,  ${originY}%`)
        $(rootEle).off('touchmove.useFormZoom').on('touchmove.useFormZoom', touchmove);
        $(rootEle).off('touchend.useFormZoom').on('touchend.useFormZoom', touchend);
      }
    };
    $(rootEle).off('touchstart.useFormZoom').on('touchstart.useFormZoom', touchstart);
  }

  function listenHeightChange() {
    try {
    } catch (e) {
    }
    let useFormZoomResizeObserver = () => {
      nextTick(() => {
        try {
          if (context.value.showLabel()) {
            try {
              window.useFormZoomResizeObserver.disconnect();
              currentZoom.value = 1
            } catch(e) {
              console.error(e)
            }
            return;
          }
          formWrapperHeight.value = getFormWrapperRect().height
          handleFormWrapperZoomWrapperSize()
        } catch(e) {
          console.error(e)
        }
      })
    };

    window.useFormZoomResizeObserver = new ResizeObserver(useFormZoomResizeObserver);
    window.useFormZoomResizeObserver.observe(formWrapper.value);
    try {
      nextTick(() => {
        formWrapperHeight.value = getFormWrapperRect().height
      })
    } catch (e) {}
  }

  function handleFormWrapperZoomWrapperSize() {
    if(context.value && context.value.showLabel()) {
      zoomWrapperWidth.value = '100%'
      zoomWrapperHeight.value = undefined
      return
    }
    try {
      zoomWrapperWidth.value = getFormWrapperRect().width ;
    } catch(e) {
    }

    try {
      zoomWrapperHeight.value = getFormWrapperRect().height ;
    } catch (e) {
    }
  }

  let getFormWrapperZoomWrapperStyle = computed(() => {
    handleFormWrapperZoomWrapperSize()
    try {
      let width = zoomWrapperWidth.value;
      if (!width || isNaN(width)) width = '100%';
      else width = width + 'px';

      let height = zoomWrapperHeight.value;
      if (!height || isNaN(height)) height = 'fit-content';
      else height = height + 'px';

      if(context.value.showLabel()) {
        height = 'auto'
      }

      return {
        width, height,
      };
    } catch (e) {
      return {
        width: '100%',
        height: 'fit-content',
      };
    }
  })
  let getFormWrapperStyle = computed(() => {
    try {
      return {
        transform: `scale(${currentZoom.value})`,
      };
    } catch (e) {
      return {
        transform: `scale(1)`,
      };
    }
  })

  function setMessage(m) {
    message.value = `${currentZoom.value}: ${m}`;
  }

  return {
    initZoom,
    getFormWrapperStyle,
    getFormWrapperZoomWrapperStyle,
    message
  };
};